/**
 * @file 项目header
 * @author wangshaozhi(wangshaozhi@baidu.com)
 */

import React, {useCallback, useEffect, useMemo} from 'react';
import {Avatar, Dropdown, Menu} from 'antd';
import {observer} from 'mobx-react';
import {useHistory} from 'react-router-dom';

// style
import cls from './index.module.scss';
import User from '../../../model/user';

interface IProps {

}

export const TopHeader: React.FC<IProps> = observer(() => {
    const history = useHistory();
    const user = useMemo(() => new User({}), []);

    useEffect(() => {
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
        if (userInfo.id) {
            user.update({
                ...userInfo
            });
        }
    }, [user]);

    const onLogout = useCallback(() => {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        history.push('/login');
    }, [history]);

    return (
        <div className={cls.avatarWrapper}>
            <Dropdown overlay={(
                <Menu>
                    <Menu.Item>个人中心</Menu.Item>
                    <Menu.Item>
                        <div onClick={onLogout}>
                            系统登出
                        </div>
                    </Menu.Item>
                </Menu>
            )}>
                <Avatar
                    className={cls.avatar}
                    src={user.avatarUrl}
                />
            </Dropdown>
        </div>
    );
});